package org.julianharty;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class DemonstrateTheService extends Activity {
	protected int counter = 17;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        /*
        serviceIntent = new Intent();
        serviceIntent.setAction("org.julianharty.LocalCounterService");
        startService(serviceIntent);
         */
        
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.click);
        button.setOnClickListener(ouch);
        button.setText("Click");
        
        bindService(new Intent(this, LocalCounterService.class), onService, BIND_AUTO_CREATE);
        // Note: the service seems to take several seconds to start, and seems
        // to start after the onCreate has completed e.g. The counter in the
        // following Toast message reflects the initial value set here, not the
        // value returned from the service.

        Toast t = Toast.makeText(this, "Counter value is: " + counter, Toast.LENGTH_LONG);
        t.show();
    }

    private OnClickListener ouch = new OnClickListener() {

		public void onClick(View arg0) {
			counter=((LocalCounterService.MyServiceBinder)service).getStatusCode();
	        Toast t = Toast.makeText(DemonstrateTheService.this, "Counter value is: " + counter, Toast.LENGTH_LONG);
	        t.show();
	        DemonstrateTheService.this.button.setText(""+counter);
		}
		
	};
	protected IBinder service;
    
    @Override
    public void onDestroy() {
    	// stopService(serviceIntent);
    	super.onDestroy();
    	
    }
    
    private ServiceConnection onService=new ServiceConnection() {
		
		public void onServiceDisconnected(ComponentName name) {
			counter = -7;
		}
		
		public void onServiceConnected(ComponentName name, IBinder service) {
			DemonstrateTheService.this.service = service;
			counter=((LocalCounterService.MyServiceBinder)service).getStatusCode();
		}
	};


	private Button button;
	
}